package com.xukai.springboot.service.statistics;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xukai.springboot.datalayer.statis.DataCaptureMapper;
import com.xukai.springboot.datalayer.statis.DataSourceMapper;
import com.xukai.springboot.entity.statistics.t_statis_datasource;
import com.xukai.springboot.util.cache.LocalCache;
import com.xukai.springboot.util.config.DatabaseContextHolder;
import com.xukai.springboot.util.constants.DataBaseType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class DataCaptureService {

    Logger logger = LoggerFactory.getLogger(DataCaptureService.class);


    /**
     * 数据源管理
     */
    @Autowired
    private DataSourceMapper dataSourceMapper;

    /**
     * 数据处理Mapper
     */
    @Autowired
    private DataCaptureMapper dataCaptureMapper;

    /**
     * 统计数据服务
     */
    @Autowired
    private StatisDataService statisDataService;

    /**
     * 获取数据
     *
     * @param sql
     * @return
     */
    public JSONObject GetData(String sql) {

        DatabaseContextHolder.setDB(DataBaseType.declare.name());
        Map<String, Object> data = dataCaptureMapper.GetData(sql);
        if (data == null) {
            return null;
        }
        JSONObject result = (JSONObject) JSONObject.toJSON(data);
        return result;
    }

    /**
     * 获取数据
     *
     * @param sql
     * @return
     */
    public JSONArray GetDataList(String sql) {
        DatabaseContextHolder.setDB(DataBaseType.declare.name());
        List<Map<String, Object>> data = dataCaptureMapper.GetDataList(sql);
        if (data == null) {
            return null;
        }
        JSONArray result = (JSONArray) JSONArray.toJSON(data);
        return result;
    }


    /**
     * 初始化数据源
     */
    public List<t_statis_datasource> GetDataSourceList() {
        DatabaseContextHolder.setDB(DataBaseType.manager.name());
        List<t_statis_datasource> datasources = (List<t_statis_datasource>) LocalCache.GetInstance().GetCache("Statis_DataSource");
        if (datasources == null) {
            datasources = dataSourceMapper.GetDataSourceList(0, "", "", "", -1, 0);
        }

        return datasources;
    }

    /**
     * 更新数据缓存
     */
    public void UpdateStatisData() {
        //获取数据源列表
        List<t_statis_datasource> dataSourceList = GetDataSourceList();
        //
        if (dataSourceList == null || dataSourceList.size() == 0) {
            return;
        }

        for (t_statis_datasource item : dataSourceList) {
            if (item.getSql().isEmpty()) {
                continue;
            }
            RefreshData(item.getDataSourceName(), item.getResultType(), item.getId(), item.getSql());
        }

    }

    /**
     * 根据数据源ID更新统计数据
     */
    public void UpdateStatisDataByID(int dataSourceID) {
        //获取数据源列表
        List<t_statis_datasource> dataSourceList = GetDataSourceList();
        //
        if (dataSourceList == null || dataSourceList.size() == 0) {
            return;
        }

        for (t_statis_datasource item : dataSourceList) {
            if (item.getSql().isEmpty()) {
                continue;
            }
            if (item.getId() == dataSourceID) {
                RefreshData(item.getDataSourceName(), item.getResultType(), item.getId(), item.getSql());
                break;
            }
        }
    }


    /**
     * 刷新数据
     *
     * @param id
     * @param sql
     */
    public void RefreshData(String dataSourceName, int resultType, int id, String sql) {
        logger.info(String.format("正在更新数据源[%s]的数据", dataSourceName));
        try {
            String jsonData = "";
            switch (resultType) {
                case 1:
                    JSONObject data = GetData(sql);
                    if (data == null) {
                        jsonData = "";
                    } else {
                        jsonData = data.toJSONString();
                    }
                    break;
                case 2:
                    JSONArray dataList = GetDataList(sql);
                    if (dataList == null) {
                        jsonData = "";
                    } else {
                        jsonData = dataList.toJSONString();
                    }
                    break;
            }
            //保存更新后的数据
            statisDataService.saveData(jsonData, id);
            dataSourceMapper.UpdateLastUPdateTime(new Date(), id);
            logger.info(String.format("数据源[%s]更新成功", dataSourceName));
        } catch (Exception ex) {
            logger.error(String.format("数据源[%s]数据更新失败", dataSourceName, ex));
        }
    }

}
